<?php

/**
 * 发送短信
 */
function sendSMS($phone, $content){
    $username = "huobull";
    $password = md5("a940826");
    $url = "http://api.smsbao.com/sms?u=$username&p=$password&m=$phone&c=".$content;
    $res = file_get_contents($url);
    return $res==0;
}

/**
 * 查询短信余额
 * $data[0] 发送条数
 * $data[1] 剩余条数
 */
function getSMSCount(){
    $username = "huobull";
    $password = md5("a940826");
    $url = "http://api.smsbao.com/query?u=".$username."&p=".$password;
    $res = file_get_contents($url);
    $arr = explode("\n", $res);
    $data = ['err', 'err'];
    if($arr[0] == 0){
        $data = explode(",", $arr[1]);
    }
    return $data;
}
function timeString($time){
    return date("Y-m-d H:i:s",$time);
}
function getFullUrl(){
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
   $url= $http_type . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   return $url;
}
/*
 * 获取当前网址的域名,包含协议
 * */
function getDomain(){
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    $url= $http_type . $_SERVER['HTTP_HOST'];
    return $url;
}
/*
 * xml转php数组
 * */
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring), true);
    return $val;
}
//数组转xml
function arrayToXml($arr) {
    $xml = "<xml>";
    foreach ($arr as $key=>$val) {
        if (is_numeric($val)) {
            $xml.="<".$key.">".$val."</".$key.">";
        } else {
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}

function weixinpay($out_trade_no, $total_fee, $body, $trade_type, $notify_url, $openid = "")
{
    /*引入微信支付*/
    require_once "ThinkPHP/Library/Vendor/WxPay/lib/WxPay.Api.php";
    $pre = array(
        'appid' => C('weixin_pay.appId'),
        'mch_id' => C('weixin_pay.MCHID'),
        'nonce_str' => create_password(32),
        'body' => $body,
        'out_trade_no' => $out_trade_no,
        'total_fee' => $total_fee * 100,
        'spbill_create_ip' => get_client_ip(),
        'notify_url' => $notify_url,
        'trade_type' => $trade_type
    );
    if ($trade_type == 'NATIVE') {
        $pre['product_id'] = $out_trade_no;
    } else if ($trade_type == 'JSAPI') {
        $pre['openid'] = $openid;
    }
    $WxPayUnifiedOrder = new WxPayUnifiedOrder();
    $WxPayUnifiedOrder->values = $pre;
    $WxPayUnifiedOrder->SetSign();
    $WxPayApi = new WxPayApi();
    $rs = $WxPayApi->unifiedOrder($WxPayUnifiedOrder);
    return $rs;
}

/**
 * @param $openid
 * @param $amount
 * @param $re_user_name
 * @param $desc
 * @return mixed
 */
function weixin_transfer_accounts($openid, $amount, $re_user_name, $desc){
    Vendor('Wxpay.lib.api');
    $appid=C('weixin_pay.appId');
    $mchid=C('weixin_pay.MCHID');
    $key=C('weixin_pay.KEY');
    $wxpay = new \api($appid, $mchid, $key);
    $res = $wxpay->zhuanzhang($openid, $amount, $re_user_name, $desc);
     return $res;



}
function dopost($param){
    $url        = $param['url'];
    $postData   = isset($param['postData'])?$param['postData']:'';
    $header     = isset($param['header'])?$param['header']:false;
    $referer    = isset($param['referer'])?$param['referer']:'';

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_HEADER, $header );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt  ($ch, CURLOPT_FOLLOWLOCATION, 1);

    if($postData){
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postData );
    }
    if($referer){
        curl_setopt ($ch, CURLOPT_REFERER, $referer);
    }
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if($SSL){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 检查证书中是否设置域名
    }

    $return = curl_exec ( $ch );
    curl_close ( $ch );
    return $return;
}

/*
/*更新微信充值订单*/
function update_chongzhi_order_weixin($parameter)
{
    $recharge_db = M('shop_recharge_order');
    $shop_db=M('shop');
    $order_where['order_number'] = $parameter['out_trade_no'];//订单号
    $order_info = $recharge_db->where($order_where)->find();
    $recharge_db->where($order_where)->setField("status", 1);
    $shop_id=$order_info['shop_id'];
    $disinfo=$shop_db->where(array('id'=>$shop_id))->find();
    $discount=$disinfo['rate']/100;
    $discount=1-$discount;
    $shop_money=$order_info['money']*$discount;
    $shop_money = sprintf("%.2f",$shop_money);//四舍五入保留两位小数
    $order_info['shop_money']=$shop_money;
    $recharge_db->where($order_where)->setField("discount", $discount);
    $recharge_db->where($order_where)->setField("paytime", time());
    $recharge_db->where($order_where)->setField("shop_money", $shop_money);
    $shop_db->where("id=" . $order_info['shop_id'])->setInc('money',  $shop_money);
}

/*
 * 生成微信不重复的随机数
 * */
function create_password($pw_length)
{
    $randpwd = "";
    for ($i = 0; $i < $pw_length; $i++) {
        $randpwd .= rand(0, 9);
    }
    return $randpwd;
}
function makeSign(){

}

//支付宝生成按钮
function alipay($out_trade_no,$subject,$money, $body="",$alipay_chongzhi_notify_url,$alipay_chongzhi_return_url){
    vendor('Alipay.AopSdk');
    vendor('Alipay.aop.AopClient');
    //构造参数
    $conf=C("alipay_conf");
    $aop = new \AopClient();
    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    $aop->appId = $conf['appId'];
    $aop->rsaPrivateKey = $conf['rsaPrivateKey'];
    $aop->apiVersion = '1.0';
    $aop->signType = 'RSA2';
    $aop->postCharset= 'utf-8';
    $aop->format='json';
    $request = new \AlipayTradePagePayRequest ();
    $request->setNotifyUrl($alipay_chongzhi_notify_url);
    $request->setReturnUrl($alipay_chongzhi_return_url);
    $product_code="FAST_INSTANT_TRADE_PAY";
    $request->setBizContent('{"product_code":"'.$product_code.'","out_trade_no":"'.$out_trade_no.'","subject":"'.$subject.'","total_amount":"'.$money.'","body":"'.$body.'"}');
    //请求
    $result = $aop->pageExecute ($request);



    //输出
    return $result;
}
/**
 * 图片上传
 * @param $file  $_FILES['thumb']
 * @param $savePath 如 apply
 * @param $saveName
 * @return array
 */
function imgUpload($file, $rootPath, $saveName, $saveExt=''){
    $upload = new \Think\Upload(array(
        'maxSize' => 0,
        'exts' => array('jpg', 'gif', 'png', 'jpeg', ''),
        'autoSub' => false,
        'rootPath' => $rootPath,
        'savePath' => "",
        'saveName' => $saveName,
        'replace' => true,
        'autoSub' => false,
        'saveExt' => $saveExt
    ));
    $img = $upload->uploadOne($file);
    if($img){
        return array(
            'success' => true,
            'path' => $rootPath.$img['savename']
        );
    }else{
        return array(
            'success' => false,
            'msg' => $upload->getError()
        );
    }
}
